import http.server
import socketserver
import os
import threading
from web import API
import webview
from port import get_usable_port

HTTP_SERVER_URL = ""

def run_http_server(port=5173, static_files_dir="dist"):
    # 获取可用端口
    port = get_usable_port(port)
    global HTTP_SERVER_URL
    
    # 确保静态文件路径为绝对路径
    static_files_dir = os.path.abspath(static_files_dir)

    class CustomHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, directory=static_files_dir, **kwargs)

    with socketserver.TCPServer(("", port), CustomHTTPRequestHandler) as httpd:
        HTTP_SERVER_URL = f"http://localhost:{port}"
        print(f"Server started on port {port} with static files directory: {static_files_dir}")
        httpd.serve_forever()

def main():
    api = API()
    
    # 设置当前工作目录为项目根目录
    project_root = os.path.dirname(os.path.abspath(__file__))
    os.chdir(project_root)

    # 启动HTTP服务器
    server_thread = threading.Thread(target=run_http_server, args=(5173, "../front/dist"))
    server_thread.daemon = True
    server_thread.start()
    
    # 等待服务器启动完成再创建窗口
    while not HTTP_SERVER_URL:
        pass

    webview.create_window('图片浏览器', HTTP_SERVER_URL, js_api=api)
    webview.start()

if __name__ == '__main__':
    main()